package com.example.myutils.excel;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class Main2 {
    public static void main(String[] args) {
        BufferedImage bufferImg = null;//图片
        try {
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("C:/Users/xyl/Desktop/test.xlsx"));
            //读取了模板内所有sheet内容
            XSSFSheet sheet = wb.getSheetAt(0);
            // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            //将图片读到BufferedImage
            bufferImg = ImageIO.read(new File("D:/images19.png"));
            // 将图片写入流中
            ImageIO.write(bufferImg, "png", byteArrayOut);
            // 利用HSSFPatriarch将图片写入EXCEL
            XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
            /**
             * 该构造函数有8个参数
             * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
             * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
             * excel中的cellNum和rowNum的index都是从0开始的
             *
             */
            //图片一导出到单元格B2中
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
                    (short) 10, 1, (short) 11, 2);
            // 插入图片
            drawingPatriarch.createPicture(anchor, wb.addPicture(byteArrayOut
                    .toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
        } catch (IOException io) {
            io.printStackTrace();
        }
    }
}
